<template>
  <div class="repair-type-page">
    <el-card>
      <div style="margin-bottom: 16px; display: flex; justify-content: space-between; align-items: center;">
        <span style="font-weight: bold;">报修类型管理</span>
        <el-button type="primary" size="small" @click="onAdd">新增类型</el-button>
      </div>
      <el-table :data="list" border stripe style="width: 100%;">
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column prop="name" label="类型名称" min-width="150" />
        <el-table-column prop="remark" label="备注" min-width="200" />
        <el-table-column prop="createTime" label="创建时间" min-width="160" />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="small" @click="onEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="onDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialog.visible" :title="dialog.isEdit ? '编辑类型' : '新增类型'" width="400px">
      <el-form :model="dialog.form" label-width="80px">
        <el-form-item label="类型名称" required>
          <el-input v-model="dialog.form.name" placeholder="请输入类型名称" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="dialog.form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialog.visible = false">取消</el-button>
        <el-button type="primary" @click="doSave">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

const list = ref([])
const fetchList = async () => {
  const res = await request.get('/repair/type/list')
  if (res.code === 1) {
    list.value = res.data
  }
}

const dialog = reactive({ visible: false, isEdit: false, form: { id: null, name: '', remark: '' } })
const onAdd = () => {
  dialog.isEdit = false
  dialog.form = { id: null, name: '', remark: '' }
  dialog.visible = true
}
const onEdit = (row) => {
  dialog.isEdit = true
  dialog.form = { ...row }
  dialog.visible = true
}
const doSave = async () => {
  if (!dialog.form.name) {
    ElMessage.warning('类型名称不能为空')
    return
  }
  if (dialog.isEdit) {
    await request.put('/repair/type', dialog.form)
    ElMessage.success('修改成功')
  } else {
    await request.post('/repair/type', dialog.form)
    ElMessage.success('新增成功')
  }
  dialog.visible = false
  fetchList()
}
const onDelete = (row) => {
  ElMessageBox.confirm('确认删除该类型？', '提示', { type: 'warning' }).then(async () => {
    await request.delete(`/repair/type/${row.id}`)
    ElMessage.success('删除成功')
    fetchList()
  })
}
onMounted(() => {
  fetchList()
})
</script>

<style scoped>
.repair-type-page {
  padding: 24px;
}
</style> 